package com.spring.wechat.web.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.spera.aliyunContent.AliyunContent;
import com.spera.genutil.TokenUtil;
import com.spera.genutil.tools;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.MyTools;
import com.spring.wechat.web.service.StoryService;
import com.wechat.api.web.dao.ChildrenStoryMapper;
import com.wechat.api.web.dao.CommonApiMapper2;
import com.wechat.api.web.dao.HostCollectionMapper;
import com.wechat.api.web.dao.StoryAlbumDetailMapper;
import com.wechat.api.web.dao.StoryAlbumMapper;
import com.wechat.api.web.dao.StoryCollectionMapper;
import com.wechat.api.web.dao.StoryCommentMapper;
import com.wechat.api.web.dao.StoryCommentPraiseMapper;
import com.wechat.api.web.dao.StoryHostMapper;
import com.wechat.api.web.dao.StoryPlayHistoryMapper;
import com.wechat.api.web.model.ChildrenStory;
import com.wechat.api.web.model.HostCollection;
import com.wechat.api.web.model.StoryAlbum;
import com.wechat.api.web.model.StoryAlbumDetail;
import com.wechat.api.web.model.StoryAlbumRequest;
import com.wechat.api.web.model.StoryCollection;
import com.wechat.api.web.model.StoryComment;
import com.wechat.api.web.model.StoryCommentPraise;
import com.wechat.api.web.model.StoryHost;
import com.wechat.api.web.model.StoryPlayHistory;

@Service
public class StoryServiceImpl implements StoryService{
	
	@Resource private JedisCache jedisCache;
	
	@Resource private StoryCommentMapper storyCommentMapper;
	
	@Resource private StoryCommentPraiseMapper storyCommentPraiseMapper;
	
	@Resource private StoryAlbumMapper storyAlbumMapper;
	
	@Resource private StoryAlbumDetailMapper storyAlbumDetailMapper;
	
	@Resource private ChildrenStoryMapper childrenStoryMapper;
	
	@Resource private StoryPlayHistoryMapper storyPlayHistoryMapper;
	
	@Resource private StoryCollectionMapper storyCollectionMapper;
	
	@Resource private CommonApiMapper2 commonApiMapper2;
	
	@Resource private HostCollectionMapper hostCollectionMapper;
	
	@Resource private StoryHostMapper storyHostMapper;
	
	
	@Override
	public BaseResult comment(StoryComment storyComment) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(storyComment.getToken(), jedisCache);
		if(br!=null){
			return br;
		}

		String user_id = jedisCache.hget(storyComment.getToken(), TokenUtil.USER_ID);
		String user_name = jedisCache.hget(storyComment.getToken(), TokenUtil.USER_NAME);
		storyComment.setUserid(user_id);
		storyComment.setUsername(user_name);		
		
		int effect=storyCommentMapper.insert(storyComment);
		
		if(effect==0){
			return new BaseResult("0","评论失败");		
		}
				
		return new BaseResult("1","评论成功");		
	}	
	
	@Override
	public BaseResult likeComment(StoryCommentPraise storyCommentPraise) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(storyCommentPraise.getToken(), jedisCache);
		if(br!=null){
			return br;
		}

		String user_id = jedisCache.hget(storyCommentPraise.getToken(), TokenUtil.USER_ID);
		String user_name = jedisCache.hget(storyCommentPraise.getToken(), TokenUtil.USER_NAME);
		storyCommentPraise.setUserid(user_id);
		storyCommentPraise.setUsername(user_name);		
		
		int count=storyCommentPraiseMapper.selectByCondition(storyCommentPraise);
		
		if(count>0){
			return new BaseResult("0","无法重复点赞");	
		}

		StoryComment storyComment=storyCommentMapper.selectByPrimaryKey(storyCommentPraise.getStoryCommentid());		
		storyComment.setPraisecount(storyComment.getPraisecount()+1);		
		storyCommentMapper.updateByPrimaryKeySelective(storyComment);
		
		int effect=storyCommentPraiseMapper.insert(storyCommentPraise);
		
		if(effect==0){
			return new BaseResult("0","点赞失败");		
		}
				
		return new BaseResult("1","点赞成功");		
	}
	
	@Override
	public BaseResult cancelLikeComment(String token,String commentID) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		
		String user_id = jedisCache.hget(token, TokenUtil.USER_ID);
		
		HashMap<String,Object> hm=new HashMap<String,Object>();
		hm.put("userID", user_id);
		hm.put("commentID", commentID);
		
		StoryCommentPraise storyCommentPraise=storyCommentPraiseMapper.selectByUser(hm);
		if(storyCommentPraise==null){
			return new BaseResult("0","该故事并未被点赞");
		}
		
/*		StoryCommentPraise storyCommentPraise=storyCommentPraiseMapper.selectByPrimaryKey(commentPraiseid);
		
		if(!storyCommentPraise.getUserid().equals(user_id)){
			return new BaseResult("0","只能取消自己的点赞");	
		}*/
		
		int effect=storyCommentPraiseMapper.deleteByPrimaryKey(storyCommentPraise.getId());
		
		StoryComment storyComment=storyCommentMapper.selectByPrimaryKey(storyCommentPraise.getStoryCommentid());		
		storyComment.setPraisecount(storyComment.getPraisecount()-1);		
		storyCommentMapper.updateByPrimaryKeySelective(storyComment);
	
		if(effect==0){
			return new BaseResult("0","取消失败");		
		}
				
		return new BaseResult("1","取消成功");		
	}
	
	@Override
	public BaseResult album(String token,String name,String desc) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		
		String user_id = jedisCache.hget(token, TokenUtil.USER_ID);
		String user_name = jedisCache.hget(token, TokenUtil.USER_NAME);
		
		String uuid = ApplicationUtils.randomUUID();
		StoryAlbum sa=new StoryAlbum();
		sa.setId(uuid);
		sa.setInitialoperatorid(user_id);
		sa.setInitialoperatorname(user_name);
		sa.setName(name);
		sa.setDesc(desc);
		
		int effect=storyAlbumMapper.insert(sa);
		br = MyTools.checkResult(effect);
		if("1".equals(br.getStatus())){
			Map<String,Object> m = new HashMap<String,Object>();
			m.put("id", uuid);
			br.setDataset(m);
		}
		return br;	
	}
	
	@Override
	public BaseResult album(String token) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		
		String user_id = jedisCache.hget(token, TokenUtil.USER_ID);
		
		List<StoryAlbum> list=storyAlbumMapper.selectByUserID(user_id);
		
		return new 	BaseResult("1","查询成功",list);
	}
	
	@Override
	public BaseResult updateAlbum(StoryAlbum storyAlbum) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(storyAlbum.getToken(), jedisCache);
		if(br!=null){
			return br;
		}		
		//String user_id = jedisCache.hget(storyAlbum.getToken(), TokenUtil.USER_ID);
		
		int effect=storyAlbumMapper.updateByPrimaryKeySelective(storyAlbum);
		
		return MyTools.checkResult(effect);
	}

	@Override
	public BaseResult albumDetail(StoryAlbumRequest storyAlbumRequest) throws Exception {	
		
		String token=storyAlbumRequest.getToken();
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		List<StoryAlbumDetail> list=storyAlbumRequest.getStoryAlbumDetail();
		int exist=0;
		for(StoryAlbumDetail temp:list){
			
			String user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			String user_name = jedisCache.hget(token, TokenUtil.USER_NAME);
			
			temp.setStoryAlbumid(storyAlbumRequest.getId());			
			temp.setInitialoperatorid(user_id);
			temp.setInitialoperatorname(user_name);
			
			int count=storyAlbumDetailMapper.checkIsExist(temp);
			if(count>0){
				exist++;
				continue;
			}
			
			int sort=storyAlbumDetailMapper.getSort(storyAlbumRequest.getId());			
			temp.setStorySort(sort);
			
			int effect = storyAlbumDetailMapper.insert(temp);
			if(effect<1){
				throw new Exception();
			}
			
		}
		if(exist>0){
			return new BaseResult("1",exist+"个收藏已存在");
		}
		
		return new BaseResult("1","操作成功");
	}
	
	
	@Override
	public BaseResult albumDetailDeleteBefore(StoryAlbumRequest storyAlbumRequest) throws Exception {	
		
		String token=storyAlbumRequest.getToken();
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		List<StoryAlbumDetail> list=storyAlbumRequest.getStoryAlbumDetail();

		HashMap<String,Object> para=new HashMap<String,Object>();
		para.put("albumID", storyAlbumRequest.getId());
		storyAlbumDetailMapper.deleteByCondition(para);
		
		int exist=0;
		for(StoryAlbumDetail temp:list){
			
			String user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			String user_name = jedisCache.hget(token, TokenUtil.USER_NAME);
			
			temp.setStoryAlbumid(storyAlbumRequest.getId());
			
			temp.setInitialoperatorid(user_id);
			temp.setInitialoperatorname(user_name);
			
			int count=storyAlbumDetailMapper.checkIsExist(temp);
			if(count>0){
				exist++;
				continue;
			}
			
			int effect = storyAlbumDetailMapper.insert(temp);
			if(effect<1){
				throw new Exception();
			}
			
		}
		if(exist>0){
			return new BaseResult("1",exist+"个收藏已存在");
		}
		
		return new BaseResult("1","操作成功");
	}
	

	@Override
	public BaseResult albumDetail(String storyAlbumid,String token,String pageSize,String pageIndex,String skip,String rows) throws Exception {	
		
		HashMap<String,Object> param=MyTools.pageIndexToSkipSearchAllLimit(pageSize, pageIndex, skip, rows);
		param.put("albumID", storyAlbumid);
		
		List<ChildrenStory> list=childrenStoryMapper.selectByAlbumID(param);
		
		int count=storyAlbumDetailMapper.selectAlubmDetailCount(storyAlbumid);

		StoryAlbum storyAlbum=storyAlbumMapper.selectByPrimaryKey(storyAlbumid);
		if(storyAlbum!=null){
			storyAlbum.setChildrenStories(list);
			storyAlbum.setCount(count);
		}
		return new BaseResult("1","操作成功",storyAlbum);
	}
	
	@Override
	public BaseResult updateAlbumDetail(StoryAlbumDetail storyAlbumDetail) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(storyAlbumDetail.getToken(), jedisCache);
		if(br!=null){
			//return br;
		}		
		
		int effect=storyAlbumDetailMapper.updateByPrimaryKeySelective(storyAlbumDetail);
		
		return MyTools.checkResult(effect);
	}
	
	@Override
	public BaseResult delAlbumDetail(String childrenStoryID,String albumID,String token) throws Exception {	
		
		HashMap<String,Object> param=new HashMap<String,Object>();
		param.put("albumID", albumID);
		param.put("storyID", childrenStoryID);
		
		int effect=storyAlbumDetailMapper.deleteByCondition(param);
		
		return MyTools.checkResult(effect);
	}
	
	
	@Override
	public BaseResult delAlbum(String albumID,String token) throws Exception {	
		
		HashMap<String,Object> param=new HashMap<String,Object>();
		param.put("albumID", albumID);

		storyAlbumDetailMapper.deleteByCondition(param);
		int effect=storyAlbumMapper.deleteByPrimaryKey(albumID);
		
		return MyTools.checkResult(effect);
	}
	
/*	@Override
	public BaseResult albumDetail(String albumID) throws Exception {			
		
		List<ChildrenStory> list= childrenStoryMapper.selectByAlbumID(albumID);
		
		return new 	BaseResult("1","查询成功",list);	
	}*/

	@Override
	public BaseResult storyCollection(String storyID,String token) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		
		String userID = jedisCache.hget(token, TokenUtil.USER_ID);
		String userName = jedisCache.hget(token, TokenUtil.USER_NAME);
		
		StoryCollection storyCollection=new StoryCollection();
		storyCollection.setInitialoperatorid(userID);
		storyCollection.setInitialoperatorname(userName);
		storyCollection.setChildrenStoryid(storyID);
		
		int count=storyCollectionMapper.checkDuplicate(storyCollection);
		if(count!=0){
			return new BaseResult("0","请勿重复收藏");
		}
		
		int effect=storyCollectionMapper.insert(storyCollection);		
		
		return MyTools.checkResult(effect);
	}
	
	@Override
	public BaseResult storyCollection(String token,String skip,String rows) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		
		String userID = jedisCache.hget(token, TokenUtil.USER_ID);
		
		HashMap<String,Object> param = MyTools.pageIndexToSkipSearchAllLimit(null, null, skip, rows);
		param.put("userID", userID);
		
		List<ChildrenStory> list=childrenStoryMapper.selectByUserID(param);
		
		return new BaseResult("1","成功",list);
	}
	
	
	@Override
	public BaseResult delStoryCollection(String hostCollectionID,String token) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		//String userID = jedisCache.hget(token, TokenUtil.USER_ID);		
		int effect=storyCollectionMapper.deleteByPrimaryKey(hostCollectionID);
		
		return MyTools.checkResult(effect);
	}
	
	@Override
	public BaseResult comment(String storyID) throws Exception {	
		
		List<StoryComment> list=storyCommentMapper.selectByStoryID(storyID);

		return new BaseResult("1","成功",list);
	}	
	
	@Override
	public BaseResult delcomment(String commentID,String token) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		int effect=storyCommentMapper.deleteByPrimaryKey(commentID);
		
		return MyTools.checkResult(effect);
	}
	
	@Override
	public BaseResult playHistory(StoryPlayHistory storyPlayHistory) throws Exception {	
		
		
		BaseResult br = TokenUtil.checkTokenBR(storyPlayHistory.getToken(), jedisCache);
		
		//storyPlayHistory.setChildrenStoryid(storyID);
		//int effect=1;
		if(br==null){
			String userID = jedisCache.hget(storyPlayHistory.getToken(), TokenUtil.USER_ID);
			String userName = jedisCache.hget(storyPlayHistory.getToken(), TokenUtil.USER_NAME);
			storyPlayHistory.setInitialoperatorid(userID);
			storyPlayHistory.setInitialoperatorname(userName);			
		}
		int effect=storyPlayHistoryMapper.insert(storyPlayHistory);	
		
		ChildrenStory childrenStory=childrenStoryMapper.selectByPrimaryKey(storyPlayHistory.getChildrenStoryid());
		childrenStory.setPlaycount(childrenStory.getPlaycount()+1);
		
		System.out.println(storyPlayHistory.getChildrenStoryid());
		System.out.println(storyPlayHistory.getLatitude());
		System.out.println(storyPlayHistory.getLongitude());
		
		int effect2=childrenStoryMapper.updateByPrimaryKeySelective(childrenStory);
	
		return MyTools.checkResult(effect2,effect);
	}
	
	@Override
	public BaseResult delPlayHistory(String storyID,String token) throws Exception {	

		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);

		if(br!=null){
			return br;
		}
		
		StoryPlayHistory storyPlayHistory=new StoryPlayHistory();
		storyPlayHistory.setChildrenStoryid(storyID);
		
		String userID = jedisCache.hget(token, TokenUtil.USER_ID);
		storyPlayHistory.setInitialoperatorid(userID);
		
		StoryPlayHistory storyPlayHistoryd=storyPlayHistoryMapper.selectByEntity(storyPlayHistory);
		int effect=storyPlayHistoryMapper.deleteByPrimaryKey(storyPlayHistoryd.getId());

		return MyTools.checkResult(effect);
	}
	

	@Override
	public BaseResult playHistory(String token,String skip,String rows) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		
		String userID = jedisCache.hget(token, TokenUtil.USER_ID);
		
		HashMap<String,Object> hm=MyTools.pageIndexToSkip(null, null, skip, rows);
		hm.put("userID", userID);
		
		List<ChildrenStory> list=childrenStoryMapper.selectHistory(hm);
		int count=childrenStoryMapper.selectHistoryCount(hm);
		
		return new BaseResult("1","成功",list,count);
	}
	
	@Override
	public  HashMap<String, Object> commitFile(String folder,String durationTime,MultipartFile file) throws Exception {

		HashMap<String, Object> m = new HashMap<String, Object>();
			if (!file.isEmpty()) {
				String fileType = tools.getFileType(file.getOriginalFilename());	
				String newfilename="";
				
				SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
				String date=sFormat.format(new Date());
				
				if(fileType!=null&&!fileType.equals("")){
				newfilename =folder+date+"/"+ ApplicationUtils.randomUUID()+ "." + fileType;
				}else{
				 newfilename =folder+date+"/"+ApplicationUtils.randomUUID();	
				}	

				int fileSize = (int) file.getSize();
					String filePath = MyTools.springFileUpOss(AliyunContent.dibabocms, newfilename, file);								
					
					String fileID=ApplicationUtils.randomUUID();
					
					HashMap<String,Object> hmp=new HashMap<String,Object>();
					hmp.put("fileID", fileID);
					hmp.put("url", filePath);
					hmp.put("osskey",newfilename);
					hmp.put("bucket", AliyunContent.dibabocms);
					hmp.put("fileType",fileType);
					hmp.put("durationTime",durationTime);
					hmp.put("fileSize",fileSize);
					hmp.put("fileName",file.getOriginalFilename());
					
					int effect=commonApiMapper2.createFile(hmp);
					if(effect<1){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "上传失败");
					}
				
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "上传成功");
					
					HashMap<String,Object> hm=new HashMap<String,Object>();
					
					hm.put("fileID", fileID);
					hm.put("url", filePath);
					
					m.put(ApplicationUtils.DATASET, hm);
							
					return m;					
			} else {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请选择上传的文件");
			}
		return m;

	}
	
	@Override
	public BaseResult userCount(String token) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		String userID = jedisCache.hget(token, TokenUtil.USER_ID);
		
		HashMap<String,Object> param = new HashMap<String,Object>();
		param.put("userID", userID);
		
		int storyAlbum = storyAlbumMapper.selectCount(userID);
		int storyPlayHistory = storyPlayHistoryMapper.selectCount(userID);
		int storyCollection = storyCollectionMapper.selectCount(userID);
		int storyHost = storyHostMapper.selectByUserIDCount(param);
		
				
		HashMap<String,Object> dataset=new HashMap<String,Object>();
		dataset.put("storyAlbum", storyAlbum);
		dataset.put("storyPlayHistory", storyPlayHistory);
		dataset.put("storyCollection", storyCollection);
		dataset.put("storyHost", storyHost);
		
		return new BaseResult("1","查询成功",dataset);	
	}

	@Override
	public BaseResult storyHost(String hostID,String token) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		
		String userID = jedisCache.hget(token, TokenUtil.USER_ID);
		String userName = jedisCache.hget(token, TokenUtil.USER_NAME);
		
		HostCollection hc=new HostCollection();
		hc.setInitialoperatorid(userID);
		hc.setInitialoperatorname(userName);
		hc.setStoryHostid(hostID);
		
		List<HostCollection> list = hostCollectionMapper.selectByCondition(hc);
		if(list.size()>0){
			return new BaseResult("0","已关注，无需重复关注");
		}
		
		int effect=hostCollectionMapper.insert(hc);
		
		return MyTools.checkResult(effect);
	}
	
	@Override
	public BaseResult delStoryHost(String hostCollectionID,String token) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}

		int effect=hostCollectionMapper.deleteByPrimaryKey(hostCollectionID);
		
		return MyTools.checkResult(effect);
	}
	
	@Override
	public BaseResult storyHost(String token,String skip,String rows) throws Exception {	
		
		BaseResult br = TokenUtil.checkTokenBR(token, jedisCache);
		if(br!=null){
			return br;
		}
		
		String userID = jedisCache.hget(token, TokenUtil.USER_ID);
		
		HashMap<String,Object> param = MyTools.pageIndexToSkip(null, null, skip, rows);
		param.put("userID", userID);
		
		List<StoryHost> list = storyHostMapper.selectByUserID(param);		
		int count=storyHostMapper.selectByUserIDCount(param);

		return new BaseResult("1","成功",list,count);
	}
	
	
}
